import datetime
import json
import time
import traceback

import requests
from bson import ObjectId
from pymongo import MongoClient

dbs = {
    "mongo": {
        "host": "118.0.1.216",
        "port": 27017,
        "username": "starviews",
        "password": "HK.bianque.27017",
        "authSource": "starviews_medical"
    }
}

mongodb_ins = MongoClient(**dbs["mongo"]).starviews_medical


def do_biz(date_st=None):
    q = {
        "app_id": ObjectId("5c9873929cc516000ecc4297"),
        "date": date_st,
        "biz_type": "2",
        "status": "1",
        "obsoleted": False,
        "his_schedule_code": {"$exists": False}
    }
    if not date_st:
        q["date"] = {"$gte": int(time.mktime(datetime.date.today().timetuple())) * 1000}
    service_objs = mongodb_ins.YYPT_Service.aggregate([
        {
            "$match": q
        },
        {
            "$lookup": {
                "from": "XHHK_Team",
                "localField": "team_id",
                "foreignField": "_id",
                "as": "team"
            }
        },
        {
            "$unwind": {
                "path": "$team",
                "preserveNullAndEmptyArrays": True
            }
        },
        {
            "$lookup": {
                "from": "YYPT_TimeQuantum",
                "localField": "time_quantum_id",
                "foreignField": "_id",
                "as": "time_quantum"
            }
        },
        {
            "$unwind": {
                "path": "$time_quantum",
                "preserveNullAndEmptyArrays": True
            }
        },
        {
            "$lookup": {
                "from": "YYPT_ServicePerson",
                "localField": "_id",
                "foreignField": "service_id",
                "as": "ser_per_map"
            }
        },
        {
            "$lookup": {
                "from": "XHHK_Person",
                "localField": "ser_per_map.person_id",
                "foreignField": "_id",
                "as": "person"
            }
        },
    ])
    for ser in service_objs:
        sch_his_p = {
            "scheduleDate": datetime.datetime.fromtimestamp(ser["date"] / 1000).strftime("%Y-%m-%d"),
            "deptName": ser["team"]["name"],
            "regName": ser["name"],
            "timeQuantum": ser["time_quantum"]["name"],
            "scheduleTag": '0',
            "option": '1',
            "doctorCode": ser["person"][0].get("his_code") if ser["person"] else "",
            "doctorName": ser["person"][0].get("name") if ser["person"] else "",
            "doctorTitle": ser["person"][0].get("posi_code") if ser["person"] else "",
            "totalAmount": ser["amount"] or 0,
            "reserveAmount": ser["amount"] or 0,
        }
        res = requests.post('http://10.246.247.248:18080/ycszyy/xhhk/services/ycszyy/v1/JMJK/createSchedule',
                            json=sch_his_p)
        if res.status_code != 200:
            print("request error")
            continue
        res_data = json.loads(res.text)
        his_schedule_code = res_data.get("MaxSerialNo")
        mongodb_ins.YYPT_Service.update_one({"_id": ser["_id"]},
                                            {"$set": {"his_schedule_code": str(his_schedule_code),
                                                      "remark": "脚本更新his_schedule_codebyapi"}})
        print(111111, str(his_schedule_code))


def main():
    try:
        do_biz(1699804800000)
    except Exception:
        print(traceback.format_exc())


if __name__ == '__main__':
    main()
